package com.bidevalution.core;

import com.bidevalution.core.constant.CharConstant;
import com.bidevalution.core.constant.LocalPathConstant;
import com.bidevalution.core.util.HttpClientUtil;
import com.qtp.core.model.Response;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 * @author huyiqi
 * @date 2019/11/11
 */
public class Common {
    private static final Logger log = LoggerFactory.getLogger(Common.class);

    private static final String URL_FORMAT = "%s%s%s";
    private static final String SLASH = "/";

    /**
     * 将文件流写到磁盘上
     * @param is 文件流
     * @param filePath 要写入的文件路径
     * @return 返回结果
     */
    public static Response<String> writeFileToDisk(InputStream is, String filePath) {
        Response<String> rsp = Response.ok(filePath);
        File file = new File(filePath);
        if(!file.getParentFile().exists()) {
            boolean dirResult = file.getParentFile().mkdirs();
            if(!dirResult) {
                return Response.fail("创建文件路径时出错");
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte[] buff = new byte[1024];
            int readed;
            while ((readed = is.read(buff)) > 0) {
                os.write(buff, 0, readed);
            }
            os.flush();
        } catch (IOException e) {
            rsp = Response.fail("写文件时出错");
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    rsp = Response.fail("关闭is时出错");
                }
            }
            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    rsp = Response.fail("关闭os时出错");
                }
            }
        }
        return rsp;
    }

    /**
     * 将数组内容用斜杠拼接
     * @param urls 需要拼接的url们
     * @return 返回拼接好的url
     */
    public static String spliceUrl(String... urls) {
        return splice(SLASH, urls);
    }

    public static String splicePath(String... paths) {
        return splice(File.separator, paths);
    }

    /**
     * 下载招标xml文件
     * @param url 下载地址
     * @return
     * @throws IOException
     */
    public static Response<String> downLoadXml(String url, String sectionCode, String localFIlePath) throws IOException {
        if(StringUtils.isBlank(url)) {
            return Response.fail("招标xml文件路径为空");
        }
        String path = Common.splicePath(localFIlePath, sectionCode);
        return HttpClientUtil.downloadFile(url, path);
    }

    public static String xmlToString(Document document, String encoding) {
        StringWriter out = new StringWriter(1024);
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);
        XMLWriter xmlWriter = new XMLWriter(out, format);
        try {
            xmlWriter.write(document);
            return out.toString();
        } catch (IOException e) {
            log.error("", e);
        } finally {
            try {
                xmlWriter.close();
            } catch (IOException e) {
                log.error("转换推送xml时出错，无法关闭xmlWriter");
            }
            try {
                out.close();
            } catch (IOException e) {
                log.error("转换推送xml时出错，无法关闭StringWriter");
            }
        }
        return null;
    }

    /**
     * 获取文件路径分隔符
     * @return 返回分隔符
     */
    private static String getPathSplitor() {
        if(!CharConstant.CHAR_LINUX_SLASH.equals(File.separator)) {
            return "\\\\";
        } else {
            return File.separator;
        }
    }

    public static String getFileNameByPath(String filePath) {
        String fileName = filePath;
        if(StringUtils.isNotBlank(filePath)) {
            String[] p = filePath.split(getPathSplitor());
            if(p.length > 0) {
                fileName = p[p.length-1];
            }
        }
        return fileName;
    }

    /**
     * 将数组内容用斜杠拼接
     * @param slash 分隔符
     * @param paths 要拼接的数组
     * @return 返回拼接好的url
     */
    private static String splice(String slash, String... paths) {
        String result = "";
        if(paths.length > 0) {
            List<String> urlList = Arrays.asList(paths);
            Iterator<String> it = urlList.iterator();
            result = it.next();
            while(it.hasNext()) {
                String left = removeRightSlash(result, slash);
                String right = removeLeftSlash(it.next(), slash);
                result = String.format(URL_FORMAT, left, slash, right);
            }
        }
        return result;
    }

    /**
     * 去掉字符串左边所有的斜杠
     * @param str 字符串
     * @return 去掉左边斜杠的字符串
     */
    private static String removeLeftSlash(String str, String slash) {
        if(StringUtils.isNotBlank(str)) {
            while (str.indexOf(slash) == 0) {
                str = str.substring(1, str.length());
            }
        }
        return str;
    }

    /**
     * 去掉字符串右边所有的斜杠
     * @param str 字符串
     * @return 去掉右边斜杠的字符串
     */
    private static String removeRightSlash(String str, String slash) {
        if(StringUtils.isNotBlank(str)) {
            int lastCharIndex = str.length() - 1;
            while (str.lastIndexOf(slash) == lastCharIndex) {
                str = str.substring(0, lastCharIndex);
                lastCharIndex = str.length() - 1;
            }
        }
        return str;
    }
}
